package com.example.pluginmanager.maven;


import com.example.pluginmanager.sftp.SftpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.shared.invoker.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

@Component
@Slf4j
public class MavenUtil {

    @Autowired
    private SftpUtil sftpUtil;

    /**
     * @param mavenPath  maven系统路径 如D:\apache-maven-3.5.4
     * @param pomPath    要操控的pom文件的系统路径 如：D:\coding\**\pom.xml
     * @param mavenOrder maven命令如：clean install
     */
    public void operationMavenOrder(String mavenPath, String pomPath, String mavenOrder, String targetPath) {
        InvocationRequest request = new DefaultInvocationRequest();
        // 设置java home
        request.setJavaHome(new File("C:\\Program Files\\Java\\jdk1.8.0_321"));
        // pom文件的位置
        request.setPomFile(new File(pomPath));
        // maven命令
        request.setGoals(Collections.singletonList(mavenOrder));

        Invoker invoker = new DefaultInvoker();
        // 设置maven_home
        invoker.setMavenHome(new File(mavenPath));

        invoker.setLogger(new PrintStreamLogger(System.err, InvokerLogger.DEBUG) {});
        // 控制台打印日志
        invoker.setOutputHandler(System.out::println);
        FileInputStream fileInputStream = null;
        try{
            InvocationResult execute = invoker.execute(request);
            if (execute.getExitCode() != 0) {
                throw new RuntimeException("打包异常");
            }
            //获取指定目录下的 .jar包
            List<File> jar = findJar(targetPath, true, new ArrayList<>());

            File file = jar.get(0);
            fileInputStream = new FileInputStream(file);
            sftpUtil.upload("/usr",file.getName(),fileInputStream);
            log.warn("发送jar : {}",file.getName());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("打包异常");
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public List<File> findJar(String targetDir, boolean flag, List<File> targetFile) {
        File dir = new File(targetDir);
        File[] files = dir.listFiles();
        for (File file : files) {
            if (flag) {
                //file是目录时，则重新调用function函数;
                if (file.isDirectory()) {
                    findJar(file.getAbsolutePath(), flag, targetFile);
                } else if (file.isFile() && file.getName().endsWith(".jar")) {
                    targetFile.add(file);
                    flag = false;
                    break;
                }
            }
        }
        return targetFile;
    }
}
